@page "/PersonalPage"
@inject NavigationManager NavigationManager
@inject AjaxService AjaxService
@using System.Diagnostics.CodeAnalysis
@using BootstrapBlazorApp.Server.Pojo
@using System.Security.Claims
@using Newtonsoft.Json;
@using BootstrapBlazorApp.Server.Components.CustomComponent

<PageTitle>个人中心</PageTitle>

<Layout ShowGotoTop="true" ShowCollapseBar="true" SideWidth="0"
        IsPage="true">
    
    <Header>
        <HeaderComponent User="@user" Type="true" PageName="个人中心"></HeaderComponent>
    </Header>
    
    
    <Main>
        @if (@EditMode)
        {
            <div class="edit">
                @* 编辑信息 *@
                <div class="edit-detail">
                    <div style="display: flex;margin-bottom: 10px">
                        <div class="col-auto col-form-label" style="width: 80px;text-align: center">
                            <span style="margin-right: 10px">昵称</span>
                        </div>
                        <div class="col-12 col-sm-6" style="width: 300px">
                            <BootstrapInput PlaceHolder="请输入昵称" @bind-Value="@newUser.NickName" ShowLabel="false"/>
                        </div>
                    </div>
                    <div style="display: flex;margin-bottom: 10px">
                        <div class="col-auto col-form-label" style="width: 80px;text-align: center">
                            <span style="margin-right: 10px">密码</span>
                        </div>
                        <div cclass="col-12 col-sm-6" style="width: 300px">
                            <BootstrapPassword PlaceHolder="请输入密码" IsSelectAllTextOnFocus="true" @bind-Value="changePasswordVo.Password"/>
                        </div>
                    </div>
                    <div style="display: flex;margin-bottom: 10px">
                        <div class="col-auto col-form-label" style="width: 80px;text-align: center">
                            <span style="margin-right: 10px">自我介绍</span>
                        </div>
                        <div class="col-12 col-sm-6" style="width: 300px;">
                            <textarea class="introduction" style="width: 300px;border-radius: 10px;border-color: #e9ecef;height: 200px" @bind="newUser.Introduction"></textarea><br>
                        </div>
                    </div>
                    <div style="display: flex;align-items: center;justify-content: center;">
                        <Button IsOutline="true" Color="Color.Danger" style="margin-right: 120px;width: 80px" @onclick="Cancel" >取消</Button>
                        <Button IsOutline="true" Color="Color.Primary" style="width: 80px" @onclick="Save">保存</Button>
                    </div>
                </div>
    
            </div>
        }
        @* left *@
        <div style="display: flex;width: 100%;height: 150%;">
            <div class="personal-left" style="background-color: rgba(252,252,253,0.82)">
                @* 头像 *@
                <div style="position: absolute; top: 0; width: 100%; background-color: rgba(238,250,253,0.77);border-radius: 10px">
                    <div style="display: flex; justify-content: center; align-items: center; height: 150px;">
                        <div>
                            <Avatar Url="@user.Avatar" Size="Size.ExtraExtraLarge" IsCircle="false"></Avatar>
                        </div>
                        <div style="display: flex;flex-direction: column;justify-content: center;margin-left: 30px">
                            <text style="font-size: 20px;margin-bottom: 20px">@user.NickName</text>
                            <text>用户名：@user.UserName</text>
                        </div>
                    </div>
                </div>
                
                @* 自我介绍 *@
                <div style="height: 200px;width: 250px;margin-top: 70px;border-radius: 10px">
                    <div style="height: 30px;text-align: center;width: auto"> 
                        <text style="font-size: 16px">个人简介</text>
                    </div>
                    <text style="font-size: 13px">@user.Introduction</text>
                </div>
                @* 按钮 *@
                <div>
                    <button class="button" style="background-color: rgba(215,246,187,0.45);color: rgba(40,151,9,0.95)" @onclick="Edit">编辑信息</button>
                </div>
                
                <div>
                    <button class="button" style="background-color: rgba(243,243,193,0.56);color: rgba(153,151,83,0.95)" @onclick="ToStar">我的收藏</button>
                </div>
                @* 退出 *@
                <div>
                    <button class="button" style="background-color: rgba(238,250,253,0.77)" >
                        <LogoutLink Url="/api/Account/Logout" Text="退出登录"/>
                    </button>
                </div>
    
            </div>
            
            <Divider IsVertical="true" Alignment="Alignment.Left"/>
            
            @* right *@
            <div class="personal-right">
                @* 进度*@
                <div class="process" style="width: 900px;height: 270px">
                    
                    @* 刷题进度 *@
                    <div style="display:flex;flex-direction: column;">
                        <text class="logo-title">刷题进度</text>
                        @if(@answerNum==0){
                        <Empty Image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" Width="133" Text="暂无数据" />
                        }else{<div style="margin-top: 30px">
                            
                            <Circle Value="@value" Color="Color.Primary" Width="150" StrokeWidth="7">
                                <div class="circle-demo">
                                    <text style="font-size:25px;">@valueString</text>
                                </div>
                            </Circle>
                        </div>}
                    </div>
                    <div class="details" style="margin-left: 80px;margin-right: 40px">
                        <div class="detail">
                            <div class="today-process" style="color:green;">简单</div>
                            <div class="today-process" style="color: green">@easy</div>
                        </div>
                        <div class="detail">
                            <div class="today-process" style="color:mediumblue">中等</div>
                            <div class="today-process" style="color:mediumblue">@medium</div>
                        </div>
                        <div class="detail">
                            <div class="today-process" style="color:indianred">困难</div>
                            <div class="today-process" style="color:indianred">@hard</div>
                        </div>
                    </div>
                    
                    <Divider IsVertical="true"></Divider>
                    
                    @* 今日完成 *@
                    <div style="display:flex;flex-direction: column;margin-left: 40px">
                        <div>
                            <text class="logo-title">今日完成</text>
                        </div>
                        <div style="display: flex;margin-top: 40px">
                            <div class="circle" style="color:green;border-color: green">
                                <span>简单</span>
                                <span>@tEasyNum</span>
                            </div>
                            <div class="circle" style="color: mediumblue;border-color: mediumblue">
                                <span>中等</span>
                                <span>@tMediumNum</span>
                            </div>
                            <div class="circle" style="color: indianred;border-color: indianred">
                                <span>困难</span>
                                <span>@tHardNum</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                @* 历史记录 *@
                <div class="history" style="margin-top: 30px">
                    <div>
                        <text class="logo-title">历史记录</text>
                    </div>
                        <div>
                            <Table TItem="Question" Items="@questions" IsStriped="true" AllowResizing="true">
                                <TableColumns>

                                    @*题目名*@
                                    <TableColumn @bind-Field="@context.Title" Width="400" Align="Alignment.Center">
                                        <Template Context="value">
                                            <a href="/Qdetail/@value.Row.Id">@value.Value</a>
                                        </Template>
                                    </TableColumn>

                                    @*题目标签*@
                                    <TableColumn @bind-Field="@context.Tag" Align="Alignment.Center">
                                        <Template Context="value">
                                            @*假设全部tag作为一个字符串存储，用、分隔*@
                                            @foreach (var tag in value.Value.Split('、'))
                                            {
                                                <div class="col-4 col-sm-auto" style="margin-right: 5px">
                                                    <Tag Color="Color.Warning">@tag</Tag>
                                                </div>
                                            }
                                        </Template>
                                    </TableColumn>

                                    @*难度*@
                                    <TableColumn @bind-Field="@context.Difficulty" Width="100" Align="Alignment.Center">
                                        <Template Context="value">
                                            <div class="@setDifficultyColor(@value.Value)">@value.Value</div>
                                        </Template>
                                    </TableColumn>
                                </TableColumns>
                            </Table>
                        </div>
                    
                </div>
            </div>
        </div>
    </Main>
</Layout>

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject MessageService MessageService
@code
{
    [NotNull]
    private Message? Message { get; set; }
    
    private bool EditMode = false;
    private ElementReference myChart;
    //刷题进度
    private int value;
    private string valueString;
    private string easy ;
    private string medium ;
    private string hard ;
    private int tEasyNum ;
    private int tMediumNum;
    private int tHardNum ;
    private int answerNum;

    private bool noHistory=true;
    
    private ClaimsPrincipal? _user;
    //用户信息
    private User user;
    
    private List<User> users = [];
    private User newUser = new();
    private List<Question> questions = [];
    private List<AnswerDetail> answerDetails= [];
    private List<AnswerDetail> tAnswerDetails= [];
    private List<QuestionWithStatus> questionsWithStatus = [];

    private ChangePasswordVo changePasswordVo = new();
    
    protected override async Task OnInitializedAsync()
    {
        base.OnInitialized();
        //获取当前用户对象
        await getUser();
        
        GetAllHistory();
        GetQuestionProcess();
    }

    private async Task getUser()
    {
        _user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
        
        if (_user == null)
        {
            return;
        }

        var value = _user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (value != null)
        {
            var user_id = int.Parse(value);
            user = User.Find(user_id);
            changePasswordVo.UserName = user.UserName;
            changePasswordVo.Password = user.Password;
        }

    }
    
    private void GetQuestionProcess(){
        var AnswerNum=AnswerDetail.Where(a=> a.UserId == user.Id).Count();
        var QuestionNum=Question.Where(q=>true).Count();
        answerNum = (int)AnswerNum;
        answerDetails=AnswerDetail.Where(a=> a.UserId == user.Id).ToList();
        DateTime today = DateTime.Today;
        tAnswerDetails=AnswerDetail.Where(a=> a.UserId == user.Id&&a.CreateTime.Date == today).ToList();
        if (answerDetails is not { Count: > 0 }) return;
        {
            value=100*(int)AnswerNum/(int)QuestionNum;
            valueString=value.ToString()+"%";
            var questionIds = answerDetails.Select(ad => ad.QuestionId).Distinct();
            var easyAnsNum = Question.Where(q => questionIds.Contains(q.Id) && q.Difficulty == "简单").Count();
            var mediumAnsNum = Question.Where(q => questionIds.Contains(q.Id) && q.Difficulty == "中等").Count();
            var hardAnsNum = Question.Where(q => questionIds.Contains(q.Id) && q.Difficulty == "困难").Count();
            var easyQuestionNum = Question.Where(q => q.Difficulty == "简单").Count();
            var mediumQuestionNum = Question.Where(q => q.Difficulty == "中等").Count();
            var hardQuestionNum = Question.Where(q => q.Difficulty == "困难").Count();
            easy=easyAnsNum+"/"+easyQuestionNum;
            medium=mediumAnsNum+"/"+mediumQuestionNum;
            hard=hardAnsNum+"/"+hardQuestionNum;
            var tQuestionIds = tAnswerDetails.Select(ad => ad.QuestionId).Distinct();
            tEasyNum = (int)Question.Where(q => tQuestionIds.Contains(q.Id) && q.Difficulty == "简单").Count();
            tMediumNum = (int)Question.Where(q => tQuestionIds.Contains(q.Id) && q.Difficulty == "中等").Count();
            tHardNum = (int)Question.Where(q => tQuestionIds.Contains(q.Id) && q.Difficulty == "困难").Count();
        }
    }
    private void GetAllHistory()
    {
        answerDetails=AnswerDetail.Where(a=> a.UserId == user.Id).ToList();
        if (answerDetails is not { Count: > 0 }) return;
        var questionIds = answerDetails.Select(ad => ad.QuestionId).Distinct();
        questions = Question
            .Where(q => questionIds.Contains(q.Id))
            .Take(6)
            .ToList();

    }
    private void Edit()
    {
        newUser = JsonConvert.DeserializeObject<User>(JsonConvert.SerializeObject(user));
        EditMode=!EditMode;
        StateHasChanged(); // 手动触发组件的重新渲染
    }

    private void ToStar()
    {
        NavigationManager.NavigateTo("/Star"); 
    }

    private void Exit()
    {
       NavigationManager.NavigateTo("/Login"); 
    }
    private void Cancel(){
        user = JsonConvert.DeserializeObject<User>(JsonConvert.SerializeObject(newUser));
        EditMode = false;
        StateHasChanged(); // 手动触发组件的重新渲染
    }
    private async Task Save()
    {
        EditMode = false;
        if (changePasswordVo.Password != user.Password)
        {
            try
            {
                // 使用Ajax调用注册API
                var document = await AjaxService.InvokeAsync(new AjaxOption()
                {
                    Url = "/api/Account/ChangePassword",
                    Data = changePasswordVo // 直接传递RegisterVo对象作为数据
                });
            }
            catch (Exception ex)
            {
                ShowMessage("修改密码失败");
            }
        }

        //保存其他信息
        try
        {
            newUser.Save();
        }
        catch (Exception ex)
        {
            ShowMessage("修改信息失败！");
        }

        await getUser();
        StateHasChanged(); // 手动触发组件的重新渲染
    }
    
    private async Task ShowMessage(string content)
    {
        Message.SetPlacement(Placement.Top);
        await MessageService.Show(new MessageOption()
        {
            Content = content
        });
    }
    
    private string setDifficultyColor(string dif)
    {
        return dif switch
        {
            "简单" => "easy-color",
            "中等" => "medium-color",
            "困难" => "hard-color",
            _ => ""
        };
    }


}
